package org.openFreely.config;

import io.netty.channel.ChannelInitializer;
import org.openFreely.exception.IllegalPortException;
import org.openFreely.exception.IllegalThreadCountsException;
import org.openFreely.starter.Starter;
import org.openFreely.utils.ClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class ClientConfig implements ApplicationRunner {

    @Autowired
    private Starter starter;

    @Value("${netty.client.messageInfo:请输入您要发送的内容}")
    private String messageInfo;

    // console 0表示默认的用户从控制台输入发送消息
    //  specified 1表示发送固定内容的消息
    @Value("${netty.client.messageType:console}")
    private String messageType;
    @Value("${netty.client.message: }")
    private String message;
    @Value("${netty.client.ip:127.0.0.1}")
    private String ip;
    @Value("${netty.client.port:9999}")
    private int port;
    @Value("${netty.client.threads:1}")
    private int threadCount;
    @Autowired(required = false)
    private ChannelInitializer channelInitializer;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        ClientUtils.setMessageInfo(messageInfo);
        if(messageType.equals("console")){
            ClientUtils.setMessageType(0);
        }else if(messageType.equals("specified")){
            ClientUtils.setMessageType(1);
            ClientUtils.setMessage(message);
        }

        ClientUtils.setIp(ip);
        if(port<=0){
            throw new IllegalPortException("非法的端口号!The port is illegal!");
        }
        ClientUtils.setPort(port);
        if(threadCount<=0){
            throw new IllegalThreadCountsException("非法的参数--线程数!The parameter threads is illegal!");
        }
        ClientUtils.setThreadCount(threadCount);
        if(channelInitializer!=null){
            ClientUtils.setChannelInitializer(channelInitializer);
        }
        starter.bootstrap();
    }
}
